﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SnmpForm.APConfig;

namespace SnmpForm.ApBatchConfig
{
    public partial class ucWlanSecure : UserControl
    {
        public ucWlanSecure()
        {
            InitializeComponent();
        }

        private List<RadioButton> radioButtonApPrimaryKeys = new List<RadioButton>();
        private List<TextBox> textBoxWepKeys = new List<TextBox>();
        private List<ComboBox> comboBoxPasswdModes = new List<ComboBox>();

        DbWrapper.DbDataTypes.WirelessSecurity m_infoWirelessSecure = null;

        public void InitWith(DbWrapper.DbDataTypes.WirelessSecurity info=null)
        {
            if(info==null)
            {
                info = new DbWrapper.DbDataTypes.WirelessSecurity();
            }
            m_infoWirelessSecure = info;
            //
            radioButtonApPrimaryKeys.Add(radioButtonApPrimaryKey1);
            radioButtonApPrimaryKeys.Add(radioButtonApPrimaryKey2);
            radioButtonApPrimaryKeys.Add(radioButtonApPrimaryKey3);
            radioButtonApPrimaryKeys.Add(radioButtonApPrimaryKey4);

            textBoxWepKeys.Add(textBoxWepKey1);
            textBoxWepKeys.Add(textBoxWepKey2);
            textBoxWepKeys.Add(textBoxWepKey3);
            textBoxWepKeys.Add(textBoxWepKey4);

            comboBoxPasswdModes.Add(comboBoxPasswdMode1);
            comboBoxPasswdModes.Add(comboBoxPasswdMode2);
            comboBoxPasswdModes.Add(comboBoxPasswdMode3);
            comboBoxPasswdModes.Add(comboBoxPasswdMode4);
            //WPA
            comboBoxApWpaMode.DataSource = AP_DEFINE_DATA.AP_WPA.Clone();
            comboBoxApCypher.DataSource = AP_DEFINE_DATA.AP_CYPHER.Clone();
            //WEP
            comboBoxApWepMode.DataSource = AP_DEFINE_DATA.AP_WEP_MODE.Clone();
            comboBoxPasswdPattern.DataSource = AP_DEFINE_DATA.PASSWD_PATTERN.Clone();

            comboBoxPasswdMode1.DataSource = AP_DEFINE_DATA.PASSWD_MODE.Clone();
            comboBoxPasswdMode2.DataSource = AP_DEFINE_DATA.PASSWD_MODE.Clone();
            comboBoxPasswdMode3.DataSource = AP_DEFINE_DATA.PASSWD_MODE.Clone();
            comboBoxPasswdMode4.DataSource = AP_DEFINE_DATA.PASSWD_MODE.Clone();

            Update();
        }

        private void UpdateViewWpa()
        {
            int nIndex = 0;
            ApConfigItem item = null;

            //WPA认证类型
            item = AP_DEFINE_DATA.find(AP_DEFINE_DATA.AP_WPA,
                m_infoWirelessSecure.wpa_mode,
                out nIndex);
            if (item != null)
            {
                comboBoxApWpaMode.SelectedIndex = nIndex;
            }
            //WPA加密算法
            item = AP_DEFINE_DATA.find(AP_DEFINE_DATA.AP_CYPHER,
                m_infoWirelessSecure.wpa_cypher,
                out nIndex);
            if (item != null)
            {
                comboBoxApCypher.SelectedIndex = nIndex;
            }

            textBoxPskKey.Text = m_infoWirelessSecure.psk_key;
            textBoxApWpaGroupReky.Text = m_infoWirelessSecure.wpa_group_rekey.ToString();
        }

        private void UpdateViewWep()
        {
            int nIndex = 0;
            ApConfigItem item = null;

            //WEP认证类型
            item = AP_DEFINE_DATA.find(AP_DEFINE_DATA.AP_WEP_MODE,
                m_infoWirelessSecure.wep_mode,
                out nIndex);
            if (item != null)
            {
                comboBoxApWepMode.SelectedIndex = nIndex;
            }

            //WEP密钥格式
            item = AP_DEFINE_DATA.find(AP_DEFINE_DATA.PASSWD_PATTERN,
                m_infoWirelessSecure.wep_passwd_pattern,
                out nIndex);
            if (item != null)
            {
                comboBoxPasswdPattern.SelectedIndex = nIndex;
            }

            //
            if (m_infoWirelessSecure.wep_key_index > 0 &&
                m_infoWirelessSecure.wep_key_index < 5)
            {
                radioButtonApPrimaryKeys[m_infoWirelessSecure.wep_key_index - 1].Checked = true;
            }
            for (nIndex = 0; nIndex < radioButtonApPrimaryKeys.Count; nIndex++)
            {
                textBoxWepKeys[nIndex].Text = m_infoWirelessSecure.wep_key[nIndex].key;
                int nItemIndex = 0;
                item = AP_DEFINE_DATA.find(AP_DEFINE_DATA.PASSWD_MODE,
                    m_infoWirelessSecure.wep_key[nIndex].passwd_mode,
                    out nItemIndex);
                if (item != null)
                {
                    comboBoxPasswdModes[nIndex].SelectedIndex = nItemIndex;
                }
            }
        }

        void UpdateView()
        {
            if (m_infoWirelessSecure != null)
            {
                switch (m_infoWirelessSecure.secmode)
                {
                    case "WPA":
                        radioButtonApSecModeWpa.Checked = true;
                        UpdateViewWpa();
                        break;
                    case "WEP":
                        radioButtonApSecModeWep.Checked = true;
                        UpdateViewWep();
                        break;
                    default:
                        radioButtonApSecModeNull.Checked = true;
                        break;
                }
            }
            else
            {
                MessageBox.Show("无法获取该AP的认证信息");
            }
        }

        public bool UpdateData()
        {
            DbWrapper.DbDataTypes.WirelessSecurity info =
               m_infoWirelessSecure;
            ApConfigItem item = null;
            //          字符串的顺序依次是（中间用#隔开）
            //--->无线安全状态(WPA)#认证类型(自动:3 WPA-PSK:1 WPA2-PSK:3)#加密算法(自动:TKIP CCMP、AES:CCMP、TKIP:TKIP)#PSK密码
            //--->无线安全状态(WEP)#认证类型(自动:4 开放系统:1 共享密钥:3)#WEP密钥格式(十六进制:0、ASCLL码:1)%密钥选择(1、2、3、4)#WEP密钥#密钥类型:(64位:64、128位:128、152位:152)
            //--->无线安全状态(None)
            if (radioButtonApSecModeNull.Checked)
            {
                info.secmode = "None";
            }
            else if (radioButtonApSecModeWpa.Checked)
            {
                info.secmode = "WPA";

                item = (ApConfigItem)comboBoxApWpaMode.SelectedValue;
                info.wpa_mode = (int)item.Value;

                item = (ApConfigItem)comboBoxApCypher.SelectedValue;
                info.wpa_cypher = (string)item.Value;

                info.psk_key = textBoxPskKey.Text;

                try
                {
                    info.wpa_group_rekey = Convert.ToInt32(textBoxApWpaGroupReky.Text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    info.wpa_group_rekey = 0;
                }
            }
            else if (radioButtonApSecModeWep.Checked)
            {
                info.secmode = "WEP";

                item = (ApConfigItem)comboBoxApWepMode.SelectedValue;
                info.wep_mode = (int)item.Value;

                item = (ApConfigItem)comboBoxPasswdPattern.SelectedValue;
                info.wep_passwd_pattern = (int)item.Value;

                int nIndex = 0;
                for (nIndex = 0; nIndex < radioButtonApPrimaryKeys.Count(); nIndex++)
                {
                    if (radioButtonApPrimaryKeys[nIndex].Checked)
                    {
                        info.wep_key_index = nIndex + 1;

                        info.wep_key[nIndex].key = textBoxWepKeys[nIndex].Text;

                        item = (ApConfigItem)comboBoxPasswdModes[nIndex].SelectedValue;
                        info.wep_key[nIndex].passwd_mode = (int)item.Value;
                    }
                }
            }
            else
            {
            }
            return true;
        }

        public void Update(bool bView = true)
        {
            if (bView)
            {
                UpdateView();
            }
            else
            {
                UpdateData();
            }
        }

        //（ASCLL合法字符"0123456789ABCDEFabcdefGHIJKLMNOPQRSTUVWXYZghijklmnopqrstuvwxyz!@#$%^&*()-=_+[]{};:\'\"\\|/?.,<>/"
        //十六进制合法字符0123456789ABCDEF）
        //8-63个ASCII码字符或8-64个十六进制字符
        private string HEX_STRING_REGULAR = "^[0123456789ABCDEF]*$";
        private string ASCII_STRING_REGULAR = "^[0123456789ABCDEFabcdefGHIJKLMNOPQRSTUVWXYZghijklmnopqrstuvwxyz!@#\\$%^&\\*\\(\\)-=_\\+\\[\\]{};:\'\"\\\\|/\\?\\.,<>/]*$";

        public bool CheckInputForWpa()
        {
            bool bValid = true;
            //检查密钥
            string strPskKey = textBoxPskKey.Text;
            if (strPskKey.Length >= 8)
            {
                bool bHex =
                    System.Text.RegularExpressions.Regex.IsMatch(strPskKey, HEX_STRING_REGULAR);
                bool bAscii =
                    System.Text.RegularExpressions.Regex.IsMatch(strPskKey, ASCII_STRING_REGULAR);

                if (bHex)
                {
                    if (strPskKey.Length > 64)
                    {
                        return false;
                    }
                }
                else if (bAscii)
                {
                    if (strPskKey.Length > 63)
                    {
                        return false;
                    }
                }
                else
                {
                    MessageBox.Show("含有非法字符");
                    return false;
                }
            }
            else
            {
                MessageBox.Show("密钥长度不正常");
                return false;
            }
            //检查组密钥周期
            string strGroupCycle = textBoxApWpaGroupReky.Text;
            if (strGroupCycle.Length > 0)
            {
                try
                {
                    int nGroupCyle = Convert.ToInt32(strGroupCycle);
                    if (nGroupCyle != 0 && nGroupCyle < 30)
                    {
                        MessageBox.Show("组密钥的更新周期不能低于30秒");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show("组密钥更新周期存在异常");
                    return false;
                }
            }
            return bValid;
        }

        public bool CheckInputForWep()
        {
            bool bValid = true;
            ApConfigItem item = null;
            item = (ApConfigItem)comboBoxPasswdPattern.SelectedValue;
            int nPattern = (int)item.Value;

            int nIndex = 0;
            for (nIndex = 0; nIndex < radioButtonApPrimaryKeys.Count(); nIndex++)
            {
                if (radioButtonApPrimaryKeys[nIndex].Checked)
                {
                    item = (ApConfigItem)comboBoxPasswdModes[nIndex].SelectedValue;
                    int nKeyTypeLen = (int)item.Value;
                    nKeyTypeLen = nKeyTypeLen / 8 - 3;

                    string strKey = textBoxWepKeys[nIndex].Text;
                    bool bHex =
                        System.Text.RegularExpressions.Regex.IsMatch(strKey, HEX_STRING_REGULAR);
                    bool bAscii =
                        System.Text.RegularExpressions.Regex.IsMatch(strKey, ASCII_STRING_REGULAR);

                    if (nPattern == 0)
                    {
                        //密码格式选择HEX
                        if (bHex)
                        {
                            //判断长度
                            //判断长度
                            if (strKey.Length == nKeyTypeLen * 2)
                            {
                            }
                            else
                            {
                                MessageBox.Show("密钥长度错误");
                                return false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("含有非法字符");
                            return false;
                        }
                    }
                    else if (nPattern == 1)
                    {
                        //密码格式选择ASCII
                        if (bAscii)
                        {
                            //判断长度
                            if (strKey.Length == nKeyTypeLen)
                            {
                            }
                            else
                            {
                                MessageBox.Show("密钥长度错误");
                                return false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("含有非法字符");
                            return false;
                        }
                    }
                    break;
                }
            }
            if (nIndex >= radioButtonApPrimaryKeys.Count)
            {
                MessageBox.Show("没有生效的密钥");
                return false;
            }
            return bValid;
        }
        public bool CheckInput()
        {
            bool bValid = true;
            if (radioButtonApSecModeNull.Checked)
            {
            }
            else if (radioButtonApSecModeWpa.Checked)
            {
                bValid = CheckInputForWpa();
            }
            else if (radioButtonApSecModeWep.Checked)
            {
                bValid = CheckInputForWep();
            }
            else
            {
            }
            return bValid;
        }

        private void comboBoxPasswdModes_SelectedIndexChanged(int nIndex, object sender, EventArgs e)
        {
            ApConfigItem item = (ApConfigItem)comboBoxPasswdModes[nIndex].SelectedItem;
            bool bEnable = !item.Value.Equals(0);
            radioButtonApPrimaryKeys[nIndex].Enabled = bEnable;
            textBoxWepKeys[nIndex].Enabled = bEnable;
        }

        private void comboBoxPasswdMode1_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxPasswdModes_SelectedIndexChanged(0, sender, e);
        }

        private void comboBoxPasswdMode2_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxPasswdModes_SelectedIndexChanged(1, sender, e);
        }

        private void comboBoxPasswdMode3_SelectedIndexChanged(object sender, EventArgs e)
        {
           comboBoxPasswdModes_SelectedIndexChanged(2, sender, e);
        }

        private void comboBoxPasswdMode4_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxPasswdModes_SelectedIndexChanged(3, sender, e);
        }

        public bool SyncToApCommitForWpa(ref string strRequest)
        {
            strRequest = "";
            DbWrapper.DbDataTypes.WirelessSecurity info =
               m_infoWirelessSecure;
            strRequest += "WPA";
            string strWpaMode = "";
            switch (info.wpa_mode)
            {
                //自动:3 WPA-PSK:1 WPA2-PSK:2
                //“AUTO”、“WPA-PSK“、”WPA2-PSK“
                case 1:
                    strWpaMode = "WPA-PSK";
                    break;
                case 2:
                    strWpaMode = "WPA2-PSK";
                    break;
                case 3:
                    strWpaMode = "AUTO";
                    break;
            }
            strRequest = strRequest + "#" + strWpaMode;

            string strWpaCypher = "";
            switch (info.wpa_cypher)
            {
                //"AUTO", "AES", "TKIP"
                //"TKIPCCMP", "CCMP", "TKIP"
                case "TKIPCCMP":
                    strWpaCypher = "AUTO";
                    break;
                case "CCMP":
                    strWpaCypher = "AES";
                    break;
                case "TKIP":
                    strWpaCypher = "TKIP";
                    break;
            }
            strRequest = strRequest + "#" + strWpaCypher;

            strRequest = strRequest + "#" + info.psk_key.ToString();
            return true;
        }

        public bool SyncToApCommitForWep(ref string strRequest)
        {
            strRequest = "";
            DbWrapper.DbDataTypes.WirelessSecurity info =
               m_infoWirelessSecure;
            strRequest += "WEP";
            string strWepMode = "";
            switch (info.wep_mode)
            {
                //自动:4 开放系统:1 共享密钥:2
                //“AUTO”、“OPEN-SYS“--"开放系统"、”SHARE-KEY“---"共享密钥"
                case 1:
                    strWepMode = "OPEN-SYS";
                    break;
                case 2:
                    strWepMode = "SHARE-KEY";
                    break;
                case 4:
                    strWepMode = "AUTO";
                    break;
            }
            strRequest = strRequest + "#" + strWepMode;


            string strWepPasswdPattern = "";
            switch (info.wep_passwd_pattern)
            {
                //十六进制:0、ASCLL码:1
                //"HEX"---"十六进制", "ASCLL"---"ASCII码", 
                case 0:
                    strWepPasswdPattern = "HEX";
                    break;
                case 1:
                    strWepPasswdPattern = "ASCLL";
                    break;
            }
            strRequest = strRequest + "#" + strWepPasswdPattern;

            strRequest = strRequest + "#" + info.wep_key_index.ToString();
            int nIndex = Convert.ToInt16(info.wep_key_index) - 1;
            strRequest = strRequest + "#" + info.wep_key[nIndex].key;
            strRequest = strRequest + "#" + info.wep_key[nIndex].passwd_mode.ToString();
            return true;
        }

        public bool GetRequst(ref string strRequest)
        {
            bool bSuccess = true;
            DbWrapper.DbDataTypes.WirelessSecurity info =
                m_infoWirelessSecure;
            strRequest = "";
            switch (info.secmode)
            {
                case "None":
                    strRequest += "None";
                    bSuccess = true;
                    break;
                case "WPA":
                    bSuccess = SyncToApCommitForWpa(ref strRequest);
                    break;
                case "WEP":
                    bSuccess = SyncToApCommitForWep(ref strRequest);
                    break;
            }
            return bSuccess;
        }
    }
}
